<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
  <title>Collabora Online Integration</title>
  <link rel="stylesheet" href="/stylesheets/style.css">
</head>

<body>
<form action="" method="get" target="" id="collabora-online-server-form">
  <label for="collabora-online-server">Collabora Online Server</label>
  <input type="text" id="collabora-online-server" name="collabora-online-server" />
  <input type="submit" name="submit" value="Load Collabora Online" />
</form>

<div style="display: none">
  <form action="" enctype="multipart/form-data" method="post" target="collabora-online-viewer" id="collabora-submit-form">
    <input name="access_token" value="" type="hidden" id="access-token"/>
    <input type="submit" value="" />
  </form>
</div>

<iframe id="collabora-online-viewer" name="collabora-online-viewer" style="width:90%;height:90%;position:absolute;">
</iframe>

<script type="text/javascript" src="javascripts/jquery-3.5.1.js"></script>

<script type="text/javascript">

var locationOrigin = window.location.origin;
var scheme = locationOrigin.startsWith('https') ? 'https' : 'http';

$("#collabora-online-server-form").submit(function(event) {
  event.preventDefault();
  var wopiClientHost = $("#collabora-online-server").val();
  if (!wopiClientHost) {
    alert('No server address entered');
    return;
  }
  if (!wopiClientHost.startsWith('http')) {
    alert('Warning! You have to specify the scheme protocol too (http|https) for the server address.')
    return;
  }
  if (!wopiClientHost.startsWith(scheme + '://')) {
    alert('Collabora Online server address scheme does not match the current page url scheme');
    return;
  }
  var wopiSrc = locationOrigin + '/wopi/files/1';
  $.getJSON("/collaboraUrl?server=" + wopiClientHost)
    .done(function( resp ) {
      var wopiClientUrl = resp['url'];
      var accessToken =  resp['token'];
      var wopiUrl = wopiClientUrl + 'WOPISrc=' + wopiSrc;
      $('#collabora-submit-form').attr('action', wopiUrl)
      $('#access-token').attr('value', accessToken);
      $('#collabora-submit-form').submit();
    })
    .fail(function( jqxhr, textStatus, error ) {
      var err = textStatus + ", " + error;
      console.log( "Request Failed: " + err );
      alert('Not possible to retrieve the complete Collabora Online url');
    });
})
</script>

</body>

</html>
